<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>朋友圈功能测试</title>
    <link rel="stylesheet" href="css/websocket-test.css">
    <style>
        .social-feed {
            display: flex;
            flex-direction: column;
            gap: 20px;
            margin-top: 20px;
        }
        
        .post {
            background-color: white;
            border-radius: 8px;
            padding: 15px;
            box-shadow: 0 2px 6px rgba(0,0,0,0.1);
        }
        
        .post-header {
            display: flex;
            align-items: center;
            margin-bottom: 10px;
        }
        
        .post-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background-color: #e0e0e0;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 10px;
            font-weight: bold;
            color: #666;
        }
        
        .post-author {
            font-weight: bold;
        }
        
        .post-time {
            margin-left: auto;
            font-size: 12px;
            color: #999;
        }
        
        .post-content {
            margin-bottom: 15px;
        }
        
        .post-text {
            margin-bottom: 10px;
            white-space: pre-wrap;
        }
        
        .post-media {
            max-width: 100%;
            border-radius: 4px;
            margin-top: 10px;
        }
        
        .post-media img {
            max-width: 100%;
            border-radius: 4px;
        }
        
        .post-media video {
            max-width: 100%;
            border-radius: 4px;
        }
        
        .post-actions {
            display: flex;
            border-top: 1px solid #eee;
            padding-top: 10px;
        }
        
        .post-action {
            flex: 1;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 5px;
            cursor: pointer;
            border-radius: 4px;
            transition: background-color 0.2s;
        }
        
        .post-action:hover {
            background-color: #f5f5f5;
        }
        
        .liked {
            color: #e53935;
        }
        
        .post-stats {
            font-size: 12px;
            color: #666;
            padding-bottom: 10px;
            border-bottom: 1px solid #eee;
            margin-bottom: 10px;
        }
        
        .post-comments {
            display: flex;
            flex-direction: column;
            gap: 10px;
        }
        
        .comment {
            background-color: #f9f9f9;
            padding: 8px 12px;
            border-radius: 6px;
            font-size: 14px;
        }
        
        .comment-author {
            font-weight: bold;
            margin-right: 5px;
        }
        
        .comment-form {
            display: flex;
            margin-top: 10px;
            gap: 8px;
        }
        
        .comment-input {
            flex: 1;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        
        .create-post {
            background-color: white;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 20px;
            box-shadow: 0 2px 6px rgba(0,0,0,0.1);
        }
        
        .create-post-header {
            font-weight: bold;
            margin-bottom: 10px;
            border-bottom: 1px solid #eee;
            padding-bottom: 10px;
        }
        
        .create-post-content {
            display: flex;
            flex-direction: column;
            gap: 10px;
        }
        
        .create-post-textarea {
            min-height: 100px;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            resize: vertical;
        }
        
        .create-post-media {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }
        
        .media-preview {
            position: relative;
            width: 100px;
            height: 100px;
            overflow: hidden;
            border-radius: 4px;
            background-color: #f0f0f0;
        }
        
        .media-preview img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        
        .media-preview video {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        
        .media-remove {
            position: absolute;
            top: 0;
            right: 0;
            background-color: rgba(0,0,0,0.5);
            color: white;
            width: 20px;
            height: 20px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            font-size: 12px;
            border-radius: 0 0 0 4px;
        }
        
        .media-preview-placeholder {
            width: 100px;
            height: 100px;
            border: 2px dashed #ddd;
            border-radius: 4px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            color: #999;
        }
        
        .create-post-actions {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-top: 10px;
        }
        
        .create-post-action {
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 5px;
            color: #666;
        }
        
        .page-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .user-status {
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .user-avatar {
            width: 36px;
            height: 36px;
            border-radius: 50%;
            background-color: #e0e0e0;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            color: #666;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="page-header">
            <h1>朋友圈功能测试</h1>
            <div class="user-status">
                <div class="user-avatar" id="userAvatar">?</div>
                <span id="userName">未登录</span>
            </div>
        </div>
        <div class="notification notification-info">
            该页面用于测试朋友圈发布、点赞、评论等社交互动功能
        </div>

        <div class="row">
            <div class="col" style="max-width: 300px;">
                <div class="card">
                    <h2 class="card-header">连接设置</h2>
                    <div class="form-group">
                        <label for="endpoint">WebSocket端点</label>
                        <input type="text" id="endpoint" value="/ChatMessageServer" placeholder="例如 /ChatMessageServer">
                    </div>
                    <div class="form-group">
                        <label for="username">您的用户名</label>
                        <input type="text" id="username" placeholder="输入用户名">
                    </div>
                    <div class="form-group">
                        <button id="connectBtn" class="btn w-100">连接</button>
                        <button id="disconnectBtn" class="btn btn-secondary w-100 mt-2" disabled>断开</button>
                    </div>

                    <div class="mt-3">
                        <div class="d-flex align-items-center">
                            <div id="statusIndicator" class="status-indicator status-offline"></div>
                            <span id="statusText">未连接</span>
                        </div>
                    </div>
                </div>
                
                <div class="card mt-3">
                    <h2 class="card-header">好友状态</h2>
                    <div class="friend-list" id="friendList">
                        <div class="text-muted text-center p-3">连接后显示好友状态</div>
                    </div>
                </div>
            </div>

            <div class="col" style="flex-grow: 2;">
                <div class="create-post">
                    <div class="create-post-header">发布朋友圈</div>
                    <div class="create-post-content">
                        <textarea id="postContent" class="create-post-textarea" placeholder="分享你的想法..."></textarea>
                        <div class="create-post-media" id="mediaPreviewContainer">
                            <div class="media-preview-placeholder" id="addMediaBtn">
                                添加图片/视频
                            </div>
                        </div>
                        <input type="file" id="mediaInput" accept="image/*,video/*" style="display: none;">
                        <div class="create-post-actions">
                            <div class="create-post-action" id="addMediaAction">
                                <span>📎</span> 添加图片/视频
                            </div>
                            <button id="publishBtn" class="btn btn-primary">发布</button>
                        </div>
                    </div>
                </div>
                
                <div class="card">
                    <h2 class="card-header">朋友圈动态</h2>
                    <div class="social-feed" id="socialFeed">
                        <div class="text-muted text-center p-5">还没有任何动态</div>
                    </div>
                </div>
            </div>
        </div>

        <div class="row mt-3">
            <div class="col">
                <div class="card">
                    <h2 class="card-header d-flex justify-content-between align-items-center">
                        <span>日志</span>
                        <button id="clearLogsBtn" class="btn btn-small btn-secondary">清空日志</button>
                    </h2>
                    <div id="logContainer" class="message-list" style="height: 200px;"></div>
                </div>
            </div>
        </div>
    </div>

    <!-- 脚本引入 -->
    <script src="js/websocket-client.js"></script>
    <script>
    // DOM元素
    const connectBtn = document.getElementById('connectBtn');
    const disconnectBtn = document.getElementById('disconnectBtn');
    const endpointInput = document.getElementById('endpoint');
    const usernameInput = document.getElementById('username');
    const statusIndicator = document.getElementById('statusIndicator');
    const statusText = document.getElementById('statusText');
    const logContainer = document.getElementById('logContainer');
    const clearLogsBtn = document.getElementById('clearLogsBtn');
    const friendList = document.getElementById('friendList');
    const socialFeed = document.getElementById('socialFeed');
    const userAvatar = document.getElementById('userAvatar');
    const userName = document.getElementById('userName');
    
    // 朋友圈相关
    const postContent = document.getElementById('postContent');
    const publishBtn = document.getElementById('publishBtn');
    const mediaInput = document.getElementById('mediaInput');
    const addMediaBtn = document.getElementById('addMediaBtn');
    const addMediaAction = document.getElementById('addMediaAction');
    const mediaPreviewContainer = document.getElementById('mediaPreviewContainer');
    
    // 变量
    let wsClient = null;
    let currentMedia = null;
    let posts = [];
    let friends = {};

    // 页面初始化
    function init() {
        // 从URL参数获取用户名和端点
        const urlParams = new URLSearchParams(window.location.search);
        if (urlParams.has('username')) {
            usernameInput.value = urlParams.get('username');
        }
        if (urlParams.has('endpoint')) {
            endpointInput.value = urlParams.get('endpoint');
        }

        // 绑定事件
        connectBtn.addEventListener('click', connect);
        disconnectBtn.addEventListener('click', disconnect);
        clearLogsBtn.addEventListener('click', clearLogs);
        publishBtn.addEventListener('click', publishPost);
        
        // 媒体上传事件
        addMediaBtn.addEventListener('click', () => mediaInput.click());
        addMediaAction.addEventListener('click', () => mediaInput.click());
        mediaInput.addEventListener('change', handleMediaSelect);
    }

    // 连接WebSocket
    function connect() {
        const endpoint = endpointInput.value.trim();
        const username = usernameInput.value.trim();

        if (!endpoint) {
            addLog('错误', 'WebSocket端点不能为空');
            return;
        }

        if (!username) {
            addLog('错误', '用户名不能为空');
            return;
        }

        // 禁用连接按钮
        connectBtn.disabled = true;
        addLog('信息', `尝试连接到 ${endpoint}...`);

        try {
            // 创建WebSocket客户端
            wsClient = new WebSocketClient(endpoint, username, {
                onConnect: handleConnect,
                onDisconnect: handleDisconnect,
                onMessage: handleMessage,
                onError: handleError,
                onReconnect: handleReconnect,
                onReconnectFailed: handleReconnectFailed
            });

            // 连接
            wsClient.connect();
        } catch (error) {
            addLog('错误', `连接初始化失败: ${error.message}`);
            connectBtn.disabled = false;
        }
    }

    // 处理连接成功
    function handleConnect() {
        // 更新UI状态
        statusIndicator.className = 'status-indicator status-online';
        statusText.textContent = '已连接';
        connectBtn.disabled = true;
        disconnectBtn.disabled = false;
        
        // 更新用户信息
        const username = usernameInput.value.trim();
        userName.textContent = username;
        userAvatar.textContent = username.charAt(0).toUpperCase();
        
        addLog('成功', '连接已建立');
        
        // 请求好友状态
        requestFriendList();
    }

    // 处理连接断开
    function handleDisconnect(event) {
        // 更新UI状态
        statusIndicator.className = 'status-indicator status-offline';
        statusText.textContent = '已断开';
        connectBtn.disabled = false;
        disconnectBtn.disabled = true;
        
        // 重置好友列表和朋友圈
        friendList.innerHTML = '<div class="text-muted text-center p-3">连接后显示好友状态</div>';
        
        addLog('信息', `连接已断开${event.code ? (' (代码: ' + event.code + ')') : ''}`);
    }

    // 处理接收消息
    function handleMessage(message) {
        addLog('收到', `接收到消息: ${message.type}`);
        
        switch (message.type) {
            case 'social_post':
                handleSocialPost(message);
                break;
            case 'social_interaction':
                handleSocialInteraction(message);
                break;
            case 'friend_status':
                handleFriendStatus(message);
                break;
            case 'system':
                addLog('系统', message.content);
                break;
            case 'error':
                addLog('错误', message.content);
                break;
        }
    }

    // 处理朋友圈发布
    function handleSocialPost(message) {
        // 添加到朋友圈列表
        addPost(message);
    }

    // 处理朋友圈互动（点赞、评论）
    function handleSocialInteraction(message) {
        const postId = message.relatedMessageId;
        const interactionType = message.content; // like, comment
        const fromUser = message.fromUser;
        const commentContent = message.comment; // 评论内容
        
        // 查找并更新对应的朋友圈
        const postIndex = posts.findIndex(post => post.messageId === postId);
        if (postIndex !== -1) {
            const post = posts[postIndex];
            
            if (interactionType === 'like') {
                // 处理点赞
                if (!post.likes) post.likes = [];
                if (!post.likes.includes(fromUser)) {
                    post.likes.push(fromUser);
                }
            } else if (interactionType === 'comment') {
                // 处理评论
                if (!post.comments) post.comments = [];
                post.comments.push({
                    fromUser: fromUser,
                    content: commentContent,
                    timestamp: message.timestamp
                });
            }
            
            // 更新对应的朋友圈显示
            updatePost(post);
        }
    }

    // 处理好友状态变更
    function handleFriendStatus(message) {
        const friend = message.fromUser;
        const status = message.content; // online, offline
        
        // 更新好友状态
        friends[friend] = status === 'online';
        
        // 更新好友列表显示
        updateFriendList();
    }

    // 处理错误
    function handleError(error) {
        addLog('错误', error.message || '发生未知错误');
    }

    // 处理重连尝试
    function handleReconnect(attempt, maxAttempts) {
        statusText.textContent = `正在重连 (${attempt}/${maxAttempts})`;
        statusText.className = 'animate-blink';
        addLog('信息', `尝试重连 (${attempt}/${maxAttempts})...`);
    }

    // 处理重连失败
    function handleReconnectFailed() {
        statusText.textContent = '重连失败';
        statusText.className = '';
        connectBtn.disabled = false;
        addLog('错误', '重连失败，已达到最大尝试次数');
    }

    // 主动断开连接
    function disconnect() {
        if (wsClient) {
            wsClient.disconnect();
        }
    }

    // 添加朋友圈
    function addPost(post) {
        // 添加到数据
        posts.unshift(post);
        
        // 移除"暂无动态"提示
        if (socialFeed.querySelector('.text-muted')) {
            socialFeed.innerHTML = '';
        }
        
        // 创建朋友圈DOM元素
        const postElement = createPostElement(post);
        
        // 添加到开头
        if (socialFeed.firstChild) {
            socialFeed.insertBefore(postElement, socialFeed.firstChild);
        } else {
            socialFeed.appendChild(postElement);
        }
    }

    // 更新朋友圈
    function updatePost(post) {
        const postElement = document.getElementById(`post-${post.messageId}`);
        if (postElement) {
            // 找到对应元素并更新
            const statsElement = postElement.querySelector('.post-stats');
            const commentsElement = postElement.querySelector('.post-comments');
            
            // 更新点赞信息
            if (post.likes && post.likes.length > 0) {
                statsElement.textContent = `${post.likes.length}个赞 · ${formatTime(post.timestamp)}`;
                
                // 更新点赞按钮样式
                const likeButton = postElement.querySelector('.post-action[data-action="like"]');
                if (post.likes.includes(usernameInput.value)) {
                    likeButton.classList.add('liked');
                } else {
                    likeButton.classList.remove('liked');
                }
            }
            
            // 更新评论
            if (post.comments && post.comments.length > 0) {
                commentsElement.innerHTML = '';
                post.comments.forEach(comment => {
                    const commentElement = document.createElement('div');
                    commentElement.className = 'comment';
                    commentElement.innerHTML = `
                        <span class="comment-author">${comment.fromUser}</span>
                        <span>${comment.content}</span>
                    `;
                    commentsElement.appendChild(commentElement);
                });
                
                // 清空评论输入框
                const commentInput = postElement.querySelector('.comment-input');
                if (commentInput) {
                    commentInput.value = '';
                }
            }
        }
    }

    // 创建朋友圈DOM元素
    function createPostElement(post) {
        const postElement = document.createElement('div');
        postElement.className = 'post';
        postElement.id = `post-${post.messageId}`;
        
        let mediaHTML = '';
        
        // 处理媒体内容
        if (post.contentType === 'image') {
            mediaHTML = `
                <div class="post-media">
                    <img src="${post.content}" alt="Post Image">
                </div>
            `;
        } else if (post.contentType === 'video') {
            mediaHTML = `
                <div class="post-media">
                    <video controls src="${post.content}"></video>
                </div>
            `;
        }
        
        const likes = post.likes || [];
        const comments = post.comments || [];
        const isLiked = likes.includes(usernameInput.value);
        
        // 构建评论HTML
        let commentsHTML = '';
        comments.forEach(comment => {
            commentsHTML += `
                <div class="comment">
                    <span class="comment-author">${comment.fromUser}</span>
                    <span>${comment.content}</span>
                </div>
            `;
        });
        
        postElement.innerHTML = `
            <div class="post-header">
                <div class="post-avatar">${post.fromUser.charAt(0).toUpperCase()}</div>
                <div class="post-author">${post.fromUser}</div>
                <div class="post-time">${formatTime(post.timestamp)}</div>
            </div>
            <div class="post-content">
                <div class="post-text">${post.text || ''}</div>
                ${mediaHTML}
            </div>
            <div class="post-stats">
                ${likes.length > 0 ? likes.length + '个赞 · ' : ''}${formatTime(post.timestamp)}
            </div>
            <div class="post-actions">
                <div class="post-action ${isLiked ? 'liked' : ''}" data-action="like" data-post-id="${post.messageId}">
                    ${isLiked ? '❤️ 已赞' : '🤍 点赞'}
                </div>
                <div class="post-action" data-action="comment" data-post-id="${post.messageId}">
                    💬 评论
                </div>
            </div>
            <div class="post-comments">
                ${commentsHTML}
            </div>
            <div class="comment-form">
                <input type="text" class="comment-input" placeholder="发表评论..." data-post-id="${post.messageId}">
                <button class="btn btn-small" onclick="submitComment('${post.messageId}')">发送</button>
            </div>
        `;
        
        // 绑定点赞和评论事件
        const likeBtn = postElement.querySelector('.post-action[data-action="like"]');
        likeBtn.addEventListener('click', () => {
            toggleLike(post.messageId);
        });
        
        const commentInput = postElement.querySelector('.comment-input');
        commentInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                submitComment(post.messageId);
            }
        });
        
        return postElement;
    }

    // 点赞/取消点赞
    function toggleLike(postId) {
        if (!wsClient || !wsClient.connected) {
            addLog('错误', '未连接到服务器');
            return;
        }
        
        const post = posts.find(p => p.messageId === postId);
        if (!post) return;
        
        const username = usernameInput.value;
        
        // 判断是否已经点赞
        const alreadyLiked = post.likes && post.likes.includes(username);
        
        // 发送点赞消息
        const message = {
            type: 'social_interaction',
            fromUser: username,
            toUser: post.fromUser,
            contentType: 'text',
            content: 'like', // 点赞类型
            relatedMessageId: postId
        };
        
        wsClient.sendMessage(message);
        
        // 更新本地状态
        if (!post.likes) post.likes = [];
        
        if (!alreadyLiked) {
            post.likes.push(username);
        }
        
        updatePost(post);
    }

    // 提交评论
    function submitComment(postId) {
        if (!wsClient || !wsClient.connected) {
            addLog('错误', '未连接到服务器');
            return;
        }
        
        const post = posts.find(p => p.messageId === postId);
        if (!post) return;
        
        const commentInput = document.querySelector(`.comment-input[data-post-id="${postId}"]`);
        const commentText = commentInput.value.trim();
        
        if (!commentText) return;
        
        // 发送评论消息
        const message = {
            type: 'social_interaction',
            fromUser: usernameInput.value,
            toUser: post.fromUser,
            contentType: 'text',
            content: 'comment', // 评论类型
            comment: commentText, // 评论内容
            relatedMessageId: postId
        };
        
        wsClient.sendMessage(message);
        
        // 更新本地状态
        if (!post.comments) post.comments = [];
        
        post.comments.push({
            fromUser: usernameInput.value,
            content: commentText,
            timestamp: Date.now()
        });
        
        updatePost(post);
    }

    // 发布朋友圈
    function publishPost() {
        if (!wsClient || !wsClient.connected) {
            addLog('错误', '未连接到服务器');
            return;
        }
        
        const content = postContent.value.trim();
        
        if (!content && !currentMedia) {
            addLog('错误', '请输入内容或添加媒体');
            return;
        }
        
        // 禁用按钮
        publishBtn.disabled = true;
        
        // 准备发送消息
        const message = {
            type: 'social_post',
            fromUser: usernameInput.value,
            contentType: currentMedia ? (currentMedia.type.startsWith('image/') ? 'image' : 'video') : 'text',
            content: currentMedia ? currentMedia.data : content,
            text: content, // 额外保存文本内容
            timestamp: Date.now()
        };
        
        // 发送消息
        wsClient.sendMessage(message);
        
        // 重置表单
        postContent.value = '';
        currentMedia = null;
        mediaPreviewContainer.innerHTML = `
            <div class="media-preview-placeholder" id="addMediaBtn">
                添加图片/视频
            </div>
        `;
        
        // 重新绑定事件
        document.getElementById('addMediaBtn').addEventListener('click', () => mediaInput.click());
        
        // 启用按钮
        publishBtn.disabled = false;
        
        addLog('发送', '已发布朋友圈');
    }

    // 处理媒体选择
    function handleMediaSelect(e) {
        const file = e.target.files[0];
        if (!file) return;
        
        if (!file.type.startsWith('image/') && !file.type.startsWith('video/')) {
            addLog('错误', '请选择有效的图片或视频文件');
            return;
        }
        
        // 读取媒体文件
        const reader = new FileReader();
        reader.onload = function(event) {
            // 存储媒体数据
            currentMedia = {
                type: file.type,
                data: event.target.result
            };
            
            // 显示预览
            mediaPreviewContainer.innerHTML = '';
            
            const mediaPreviewDiv = document.createElement('div');
            mediaPreviewDiv.className = 'media-preview';
            
            if (file.type.startsWith('image/')) {
                mediaPreviewDiv.innerHTML = `
                    <img src="${event.target.result}" alt="媒体预览">
                    <div class="media-remove">&times;</div>
                `;
            } else if (file.type.startsWith('video/')) {
                mediaPreviewDiv.innerHTML = `
                    <video src="${event.target.result}" muted></video>
                    <div class="media-remove">&times;</div>
                `;
            }
            
            mediaPreviewContainer.appendChild(mediaPreviewDiv);
            
            // 添加媒体预览占位符
            const placeholderDiv = document.createElement('div');
            placeholderDiv.className = 'media-preview-placeholder';
            placeholderDiv.id = 'addMediaBtn';
            placeholderDiv.textContent = '添加图片/视频';
            
            mediaPreviewContainer.appendChild(placeholderDiv);
            
            // 重新绑定事件
            document.getElementById('addMediaBtn').addEventListener('click', () => mediaInput.click());
            
            // 移除按钮事件
            const removeBtn = mediaPreviewDiv.querySelector('.media-remove');
            removeBtn.addEventListener('click', function() {
                currentMedia = null;
                mediaPreviewContainer.innerHTML = `
                    <div class="media-preview-placeholder" id="addMediaBtn">
                        添加图片/视频
                    </div>
                `;
                document.getElementById('addMediaBtn').addEventListener('click', () => mediaInput.click());
            });
        };
        
        reader.readAsDataURL(file);
    }

    // 请求好友列表
    function requestFriendList() {
        // 在实际应用中，这里应该发送请求获取完整好友列表
        // 在本测试中，我们依靠好友状态变更消息来更新列表
        addLog('信息', '等待好友状态更新...');
    }

    // 更新好友列表显示
    function updateFriendList() {
        // 清空现有列表
        friendList.innerHTML = '';
        
        // 检查是否有好友
        const hasFriends = Object.keys(friends).length > 0;
        
        if (!hasFriends) {
            friendList.innerHTML = '<div class="text-muted text-center p-3">没有好友在线</div>';
            return;
        }
        
        // 添加每个好友
        for (const [friend, isOnline] of Object.entries(friends)) {
            const friendElement = document.createElement('div');
            friendElement.className = 'd-flex align-items-center justify-content-between p-2';
            
            // 简单的第一个字符作头像
            const firstChar = friend.charAt(0).toUpperCase();
            
            friendElement.innerHTML = `
                <div class="d-flex align-items-center">
                    <div class="user-avatar" style="width:30px;height:30px;font-size:12px;">${firstChar}</div>
                    <span class="ms-2">${friend}</span>
                </div>
                <span class="status-indicator ${isOnline ? 'status-online' : 'status-offline'}"></span>
            `;
            
            friendList.appendChild(friendElement);
        }
    }
    
    // 格式化时间
    function formatTime(timestamp) {
        const date = new Date(timestamp);
        return date.toLocaleString();
    }

    // 添加日志
    function addLog(level, message) {
        const logItem = document.createElement('div');
        logItem.className = 'message-item animate-fade-in';
        
        const timeStr = new Date().toLocaleTimeString();
        let levelClass = '';
        
        switch (level.toLowerCase()) {
            case '错误':
                levelClass = 'text-danger';
                break;
            case '成功':
                levelClass = 'text-success';
                break;
            case '信息':
                levelClass = 'text-muted';
                break;
            case '系统':
                levelClass = 'text-primary';
                break;
            case '收到':
                levelClass = 'text-success';
                break;
            case '发送':
                levelClass = 'text-primary';
                break;
            default:
                levelClass = '';
        }
        
        logItem.innerHTML = `
            <div class="message-header">
                <span class="message-sender ${levelClass}">[${level}]</span>
                <span class="message-time">${timeStr}</span>
            </div>
            <div class="message-content">${message}</div>
        `;
        
        logContainer.appendChild(logItem);
        logContainer.scrollTop = logContainer.scrollHeight;
    }

    // 清空日志
    function clearLogs() {
        logContainer.innerHTML = '';
    }

    // 初始化页面
    document.addEventListener('DOMContentLoaded', init);
    </script>
</body>
</html> 